package com.example.login;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.example.security.InfoDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class OAuth2TokenService {


    @Autowired
    private Environment environment;

    public Map generateAccessToken(InfoDetail infoDetail) {

        HashMap<String, Object> objectHashMap = new HashMap<>();
        objectHashMap.put("grant_type", AuthorizationGrantType.PASSWORD.getValue());
        objectHashMap.put("username", infoDetail.getUsername());
        objectHashMap.put("password", infoDetail.getPassword());
        objectHashMap.put("scope", infoDetail.getScopes());

        String clientId = infoDetail.getClientId();
        String clientSecret = infoDetail.getClientSecret();
        String body = HttpRequest.post(environment.getProperty("spring.security.oauth2.resourceserver.jwt.issuer-uri") + "/oauth2/token")
                .basicAuth(clientId, clientSecret)
                .contentType("application/x-www-form-urlencoded") // 明确指定 Content-Type
                .form(objectHashMap)
                .execute().body();
        return JSONUtil.toBean(body, Map.class);
    }
}